/**
 * 微信小程序API兼容性处理工具
 * 用于解决各种平台和版本差异导致的API不兼容问题
 */

// 空函数，用于拦截不支持的API调用
const noop = function() {
  return Promise.resolve({errMsg: 'ok'});
};

/**
 * 修复reportRealtimeAction不支持的问题
 * 这个问题在某些设备或低版本基础库中会出现
 */
function fixReportRealtimeAction() {
  // 如果API不存在，直接设置为空函数
  if (typeof wx.reportRealtimeAction === 'undefined') {
    wx.reportRealtimeAction = noop;
    return;
  }

  // 如果API存在但可能不支持，重写它
  try {
    // 保存原始函数引用
    const originalReportAction = wx.reportRealtimeAction;
    
    // 重写函数，添加错误处理
    wx.reportRealtimeAction = function(...args) {
      try {
        // 尝试调用原始函数
        return originalReportAction.apply(wx, args);
      } catch (e) {
        // 捕获并忽略错误
        console.log('reportRealtimeAction 调用失败，已被忽略');
        return Promise.resolve({errMsg: 'reportRealtimeAction:ok'});
      }
    };
  } catch (e) {
    // 如果重写过程中出错，直接设置为空函数
    wx.reportRealtimeAction = noop;
  }
}

/**
 * 处理Workers环境中的reportRealtimeAction问题
 */
function fixWorkerReportAction() {
  // 检测是否在Worker环境中
  const isWorkerEnv = typeof self !== 'undefined' && typeof self.WorkerGlobalScope !== 'undefined';
  
  // 处理WebWorker环境
  if (typeof worker !== 'undefined') {
    try {
      // 确保worker对象存在reportRealtimeAction方法
      if (typeof worker.reportRealtimeAction === 'undefined') {
        Object.defineProperty(worker, 'reportRealtimeAction', {
          configurable: true,
          writable: true,
          value: function(...args) {
            return Promise.resolve({errMsg: 'reportRealtimeAction:ok'});
          }
        });
      }
    } catch(e) {
      console.log('worker对象处理失败，忽略', e);
    }
  }

  // 处理globalThis环境
  if (typeof globalThis !== 'undefined') {
    try {
      if (typeof globalThis.reportRealtimeAction === 'undefined') {
        Object.defineProperty(globalThis, 'reportRealtimeAction', {
          configurable: true,
          writable: true,
          value: function(...args) {
            return Promise.resolve({errMsg: 'reportRealtimeAction:ok'});
          }
        });
      }
    } catch(e) {
      console.log('globalThis对象处理失败，忽略', e);
    }
  }
  
  // 如果在Worker环境中，直接劫持Worker上下文的wx对象
  if (isWorkerEnv && typeof self.wx !== 'undefined') {
    try {
      if (typeof self.wx.reportRealtimeAction === 'undefined') {
        self.wx.reportRealtimeAction = function(...args) {
          return Promise.resolve({errMsg: 'reportRealtimeAction:ok'});
        };
      } else {
        // 保存原始函数引用
        const originalReportAction = self.wx.reportRealtimeAction;
        
        // 重写函数，添加错误处理
        self.wx.reportRealtimeAction = function(...args) {
          try {
            return originalReportAction.apply(self.wx, args);
          } catch (e) {
            return Promise.resolve({errMsg: 'reportRealtimeAction:ok'});
          }
        };
      }
    } catch (e) {
      console.log('Worker环境wx对象处理失败，忽略', e);
    }
  }
}

/**
 * 提供reportRealtimeAction的安全调用版本
 */
function safeReportRealtimeAction(name, data) {
  try {
    if (typeof wx.reportRealtimeAction === 'function') {
      return wx.reportRealtimeAction(name, data);
    }
  } catch (e) {
    console.log('安全调用reportRealtimeAction失败', e);
  }
  return Promise.resolve({errMsg: 'reportRealtimeAction:ok'});
}

/**
 * 修复所有与performance/analytics相关的API
 */
function fixPerformanceAPIs() {
  // 处理performanceReport
  if (typeof wx.reportPerformance === 'undefined') {
    wx.reportPerformance = noop;
  } else {
    try {
      const originalReportPerformance = wx.reportPerformance;
      wx.reportPerformance = function(...args) {
        try {
          return originalReportPerformance.apply(wx, args);
        } catch (e) {
          return Promise.resolve({errMsg: 'reportPerformance:ok'});
        }
      };
    } catch (e) {
      wx.reportPerformance = noop;
    }
  }

  // 处理reportAnalytics
  if (typeof wx.reportAnalytics === 'function') {
    try {
      const originalReportAnalytics = wx.reportAnalytics;
      wx.reportAnalytics = function(...args) {
        try {
          return originalReportAnalytics.apply(wx, args);
        } catch (e) {
          return Promise.resolve({errMsg: 'reportAnalytics:ok'});
        }
      };
    } catch (e) {
      wx.reportAnalytics = noop;
    }
  }
}

/**
 * 添加全局错误处理，过滤掉reportRealtimeAction相关错误
 */
function setupGlobalErrorHandlers() {
  // 监听未捕获的全局错误
  wx.onError(function(err) {
    if (typeof err === 'string' && 
       (err.includes('reportRealtimeAction') || 
        err.includes('not support') || 
        err.includes('performance') ||
        err.includes('analytics'))) {
      console.log('全局错误监听器已捕获并忽略错误:', err);
      return;
    }
    
    // 其他错误正常处理并上报
    console.error('全局错误:', err);
  });

  // 监听未处理的Promise异常
  wx.onUnhandledRejection(function(res) {
    const { reason } = res;
    
    // 检查错误字符串
    if (reason && typeof reason === 'string' && 
       (reason.includes('reportRealtimeAction') || 
        reason.includes('not support') ||
        reason.includes('performance') ||
        reason.includes('analytics'))) {
      console.log('全局Promise错误监听器已捕获并忽略错误:', reason);
      return;
    }
    
    // 检查错误对象
    if (reason && reason.errMsg && typeof reason.errMsg === 'string' && 
       (reason.errMsg.includes('reportRealtimeAction') || 
        reason.errMsg.includes('not support') ||
        reason.errMsg.includes('performance') ||
        reason.errMsg.includes('analytics'))) {
      console.log('全局Promise错误监听器已捕获并忽略错误:', reason.errMsg);
      return;
    }
    
    // 其他异常正常处理
    console.error('未处理的Promise异常:', res);
  });
}

/**
 * 运行所有修复
 */
function runAllFixes() {
  try {
    // 修复实时动作上报
    fixReportRealtimeAction();
    
    // 修复Worker环境
    fixWorkerReportAction();
    
    // 修复性能分析API
    fixPerformanceAPIs();
    
    // 设置全局错误处理
    setupGlobalErrorHandlers();
    
    console.log('WX API 兼容性修复已应用');
  } catch (e) {
    console.error('WX API 兼容性修复失败', e);
  }
}

module.exports = {
  noop,
  fixReportRealtimeAction,
  fixWorkerReportAction,
  safeReportRealtimeAction,
  fixPerformanceAPIs,
  setupGlobalErrorHandlers,
  runAllFixes
}; 